<?php
declare(strict_types=1);
/**
 * Author: Traveler
 * Time  : 2021/9/3 11:46
 */

namespace sunshine\basic;


/**
 * Class BaseService
 *
 * @package sunshine\basic
 */
abstract class BaseService
{
    /**
     * 模型
     *
     * @var BaseModel
     */
    protected $model;

    /**
     * 动态query条件
     *
     * @var array
     */
    protected $queryConditions;

    /**
     * 是否将结果列表转换至树形结构
     *
     * @var string
     */
    protected $isTreeResult;

    /**
     * 根据指定条件获取统计
     *
     * @param array $where 查询条件
     * @return int
     */
    public function getCountByWhere(array $where): int
    {
        return $this->model->where($where)->count();
    }

    /**
     * 获取分页
     *
     * @param array $param  参数数组
     * @param bool  $remove 是否从参数数组中移除分页参数
     * @return int[]
     */
    protected function getPagination(array &$param, bool $remove = true): array
    {
        $limit = isset($param['limit']) ? (int)$param['limit'] : 0;
        // 当 limit 为 0 时，page 始终为 1
        $page = $limit === 0 || !isset($param['page']) ? 1 : (int)$param['page'];

        if ($remove) {
            unset($param['page']);
            unset($param['limit']);
        }

        return [$page, $limit];
    }

    /**
     * 过滤无效参数(空字符串，null，boolean)
     *
     * @param array $param 参数数组
     * @return array
     */
    protected function filterInvalidParam(array $param): array
    {
        return array_filter($param, function ($v) {
            return is_numeric($v) || !empty($v) && !is_bool($v);
        });
    }

    /**
     * 生成完整的搜索条件
     *
     * @return array
     */
    protected function makeConditions(): array
    {
        return [
            'where'      => $this->queryConditions['where'] ?? [],
            'field'      => $this->queryConditions['field'] ?? [],
            'visible'    => $this->queryConditions['visible'] ?? [],
            'hidden'     => $this->queryConditions['hidden'] ?? [],
            'with'       => $this->queryConditions['with'] ?? [],
            'append'     => $this->queryConditions['append'] ?? [],
            'order'      => $this->queryConditions['order'] ?? []
        ];
    }
}